<?php

class Admin_LoginController extends Zend_Controller_Action {

    public function init() {
        $this->view->bodyId = "id='login'";
    }

    public function indexAction() {
        $form = new Admin_Form_Login();
        $this->view->loginForm = $form;

        $paramError = $this->getRequest()->getParam('err');

        if ($paramError == 1){
            if (isset($this->view->errors)){
                $this->view->errors[] = 'No tiene permiso para ingresar a esta pagina';
            }else{
                $this->view->errors = array('No tiene permiso para ingresar a esta pagina');
            }
        }
    }

    public function processAction() {
        $request = $this->getRequest();

        // Check if we have a POST request
        if (!$request->isPost()) {
            return $this->_helper->redirector('index');
        }

        // Get our form and validate it
        $form = $form = new Admin_Form_Login();
        if (!$form->isValid($request->getPost())) {
            // Invalid entries
            $this->view->loginForm = $form;
            $errorsMessages = $form->getMessages();
            $errors = array();
            if (isset($errorsMessages['username']['isEmpty'])) {
                $errors[] = "Usuario no ingresado";
            }
            if (isset($errorsMessages['passwd']['isEmpty'])) {
                $errors[] = "Contrase&ntilde;a no ingresada";
            }
            $this->view->errors = $errors;
            return $this->render('index'); // re-render the login form
        } else {

            // Do the LOGIN
            $formData = $this->_request->getPost();
            $authAdapter = new Nosql_Auth_Adapter($formData['username'], $formData['passwd']);
            $result = Zend_Auth::getInstance()->authenticate($authAdapter);
            if (Zend_Auth::getInstance()->hasIdentity()) {
                $this->_redirect('/admin/');
                return;
            } else {
                $this->view->errors = array(implode(' ', $result->getMessages()));
            }
        }

        $this->view->loginForm = $form;
        return $this->render('index'); // re-render the login form
    }

    public function logoutAction(){
        if (Zend_Auth::getInstance()->hasIdentity()){
            Zend_Auth::getInstance()->clearIdentity();
        }

        return $this->_redirect('/');

    }

}

